package com.liqi.web.controller.openapi.middleware;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.liqi.device.domain.DvGroup;
import com.liqi.system.domain.SysRegion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.liqi.common.core.controller.BaseController;
import com.liqi.common.core.domain.R;
import com.liqi.common.utils.DateUtils;
import com.liqi.common.utils.StringUtils;
import com.liqi.common.utils.uuid.GenerateCodeUtils;
import com.liqi.deployment.domain.DvDeployment;
import com.liqi.deployment.domain.DvDeploymentModule;
import com.liqi.deployment.domain.DvOperationUser;
import com.liqi.deployment.service.IDvDeploymentModuleService;
import com.liqi.deployment.service.IDvDeploymentService;
import com.liqi.device.domain.DvDevice;
import com.liqi.device.domain.DvDeviceModule;
import com.liqi.device.service.IDvBrandService;
import com.liqi.device.service.IDvDeviceModuleService;
import com.liqi.device.service.IDvDeviceService;
import com.liqi.device.service.IDvGroupService;
import com.liqi.device.service.IDvManufacturerService;
import com.liqi.device.service.IDvModuleService;
import com.liqi.monitor.service.IDvDeploymentSystemService;
import com.liqi.system.domain.dto.RegionDto;
import com.liqi.system.service.ISysDeptService;
import com.liqi.system.service.ISysRegionService;
import com.liqi.system.service.device.IDvOperationUserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 设备部署信息维护 Controller
 *
 * @author xiaoli
 * @date 2022-02-14
 */
@Api(tags = "提供给中间件的接口")
@RestController
@RequestMapping("/openApi/middleware")
public class DvDeploymentInfoController extends BaseController {
	@Autowired
	private IDvDeploymentService dvDeploymentService;

	@Autowired
	private IDvDeviceService dvDeviceService;

	@Autowired
	private ISysRegionService sysRegionService;

	@Autowired
	private IDvOperationUserService dvOperationUserService;

	@Autowired
	private IDvBrandService dvBrandService;

	@Autowired
	private IDvManufacturerService dvManufacturerService;

	@Autowired
	private IDvDeploymentModuleService dvDeploymentModuleService;

	@Autowired
	private IDvDeviceModuleService dvDeviceModuleService;

	@Autowired
	private IDvGroupService dvGroupService;

	@Autowired
	private ISysDeptService deptService;

	@Autowired
	private IDvDeploymentSystemService dvDeploymentSystemService;

	@Autowired
	private IDvModuleService dvModuleService;





	/**
	 * 保存设备部署信息
	 */
	@ApiOperation("保存设备部署信息")
	@PostMapping("/saveDeploymentInfo")
	public R saveDeploymentInfo(@RequestBody DvDeployment dvDeployment) {
		try {
			if (StringUtils.isBlank(dvDeployment.getDeviceId())) {
				return R.fail("设备id不能为空");
			}
			if (StringUtils.isBlank(dvDeployment.getDeploymentName())) {
				return R.fail("部署名称不能为空");
			}
			if (StringUtils.isBlank(dvDeployment.getDeviceCode())) {
				return R.fail("设备代码不能为空");
			}
			if (StringUtils.isBlank(dvDeployment.getDeviceName())) {
				return R.fail("设备名称不能为空");
			}
			if (StringUtils.isBlank(dvDeployment.getRegionId())) {
				return R.fail("投放区域不能为空");
			}
			if (StringUtils.isBlank(dvDeployment.getGroupId())) {
				return R.fail("投放分组不能为空");
			}
			if (StringUtils.isBlank(dvDeployment.getIpAddress())) {
				return R.fail("ip地址不能为空");
			}
			String deviceId = dvDeployment.getDeviceId();
			DvDeployment deployment = null;
			if (StringUtils.isNotBlank(deviceId)) {
				deployment = dvDeploymentService.getByDeviceId(deviceId);
			}
			if (deployment == null) {
				String operationUserCode = dvDeployment.getOperationUserCode();
				String operationUserName = dvDeployment.getOperationUserName();// 获取运维人员姓名
				String phoneNumber = dvDeployment.getPhoneNumber();// 获取运维负责人电话
				DvOperationUser dvOperationUser = null;
				if (StringUtils.isNotBlank(operationUserCode)) {
					dvOperationUser = dvOperationUserService.selectDvOperationUserByCode(operationUserCode);
				} else if (StringUtils.isNotBlank(operationUserName) && StringUtils.isNotBlank(phoneNumber)) {
					DvOperationUser dvOperationUserParams = new DvOperationUser();// 使用运维人员姓名和电话搜索运维人员表，返回集合
					dvOperationUserParams.setOperationUserName(operationUserName);
					dvOperationUserParams.setPhoneNumber(phoneNumber);
					List<DvOperationUser> dvOperationUsers = dvOperationUserService.selectDvOperationUserByNameOrPhone(dvOperationUserParams);
					if (dvOperationUsers.size() != 0) {
						dvOperationUser = dvOperationUsers.get(0);
					}
				} else {
					return R.fail("运维人员姓名和电话不能为空，请重新确认");
				}
				if (dvOperationUser == null) {
					dvOperationUser = new DvOperationUser();
					dvOperationUser.setOperationUserCode(GenerateCodeUtils.getSequnce());
					dvOperationUser.setOperationUserName(operationUserName);
					dvOperationUser.setPhoneNumber(phoneNumber);
					dvOperationUser.setSex("0");
					dvOperationUser.setStatus(0);
					dvOperationUser.setCreateBy(operationUserName);
					dvOperationUser.setCreateTime(DateUtils.getNowDate());
					dvOperationUser.setUpdateBy(operationUserName);
					dvOperationUser.setUpdateTime(DateUtils.getNowDate());
					dvOperationUser.setDeptId("120");//开发时，还没有确定部门，但是设备投放部门id不能为空，先写OperationUserCode
					dvOperationUser.setCreateUserId(dvDeployment.getOperationUserCode());
					dvOperationUserService.insertDvOperationUser(dvOperationUser);//插入一条运维人员信息数据
				}
				dvDeployment.setCreateBy(dvOperationUser.getOperationUserName());
				dvDeployment.setCreateUserId(dvOperationUser.getOperationUserCode());
				dvDeployment.setUpdateBy(dvOperationUser.getOperationUserName());
				dvDeployment.setPhoneNumber(dvOperationUser.getPhoneNumber());
				dvDeployment.setDeptId(dvOperationUser.getDeptId());
				String deviceCode = dvDeployment.getDeviceCode();// 获取参数设备码
				DvDevice dvDevice = dvDeviceService.selectDvDeviceByCode(deviceCode);// 根据设备码找到即将要投放的设备
				List<DvDeviceModule> dvDeviceModules = dvDeviceModuleService
						.selectDvDeviceModuleListByDeviceCode(deviceCode);// 根据设备码列出将要投放的设备的所有模块，返回模块列表
				for (DvDeviceModule dvDeviceModule : dvDeviceModules) {// 遍历设备模块列表，对应每个模块创建一个部署设备模块对象
					DvDeploymentModule DvDeploymentModule = new DvDeploymentModule();
					DvDeploymentModule.setDeviceId(dvDeployment.getDeviceId());
					DvDeploymentModule.setDeviceName(dvDevice.getName());
					DvDeploymentModule.setDeviceCode(dvDeployment.getDeviceCode());
					DvDeploymentModule.setModelCode(dvDeviceModule.getModuleCode());
					DvDeploymentModule.setModelName(dvDeviceModule.getModuleName());
					DvDeploymentModule.setModelStatus(0);
					DvDeploymentModule.setCreateBy(dvOperationUser.getOperationUserName());
					DvDeploymentModule.setUpdateBy(dvOperationUser.getOperationUserName());
					DvDeploymentModule.setCreateTime(DateUtils.getNowDate());
					DvDeploymentModule.setUpdateTime(DateUtils.getNowDate());
					dvDeploymentModuleService.insertDvDeploymentModule(DvDeploymentModule);// 插入一条投放设备数据
				}
				SysRegion region = sysRegionService.selectSysRegionById(dvDeployment.getRegionId());
				if (region != null) {
					dvDeployment.setAncestors(region.getAncestors());
					Long parentId = region.getParentId();
					if (parentId != 0) {
						SysRegion parent = sysRegionService.selectSysRegionById(parentId.toString());
						dvDeployment.setAncestorsName(parent.getName());
					}
				}
				DvGroup group = dvGroupService.selectDvGroupById(Long.parseLong(dvDeployment.getGroupId()));
				if (group != null) {
					dvDeployment.setGroupName(group.getName());
					dvDeployment.setGroupAncestors(group.getAncestors());
				}
				dvDeployment.setDeploymentCode(GenerateCodeUtils.getSequnce());
				dvDeployment.setDeviceStatus("1");
				dvDeployment.setCreateTime(DateUtils.getNowDate());
				dvDeployment.setUpdateTime(DateUtils.getNowDate());
				dvDeployment.setStatus(0);
			} else {
				String operationUserCode = dvDeployment.getOperationUserCode();
				String operationUserName = dvDeployment.getOperationUserName();// 获取运维人员姓名
				String phoneNumber = dvDeployment.getPhoneNumber();// 获取运维负责人电话
				DvOperationUser dvOperationUser = null;
				if (StringUtils.isNotBlank(operationUserCode)) {
					dvOperationUser = dvOperationUserService.selectDvOperationUserByCode(operationUserCode);
				} else if (StringUtils.isNotBlank(operationUserName) && StringUtils.isNotBlank(phoneNumber)) {
					DvOperationUser dvOperationUserParams = new DvOperationUser();// 使用运维人员姓名和电话搜索运维人员表，返回集合
					dvOperationUserParams.setOperationUserName(operationUserName);
					dvOperationUserParams.setPhoneNumber(phoneNumber);
					List<DvOperationUser> dvOperationUsers = dvOperationUserService.selectDvOperationUserByNameOrPhone(dvOperationUserParams);
					if (dvOperationUsers.size() != 0) {
						dvOperationUser = dvOperationUsers.get(0);
					}
				} else {
					return R.fail("运维人员姓名和电话不能为空，请重新确认");
				}
				if (dvOperationUser == null) {
					dvOperationUser = new DvOperationUser();
					dvOperationUser.setOperationUserCode(GenerateCodeUtils.getSequnce());
					dvOperationUser.setOperationUserName(operationUserName);
					dvOperationUser.setPhoneNumber(phoneNumber);
					dvOperationUser.setSex("0");
					dvOperationUser.setStatus(0);
					dvOperationUser.setCreateBy(operationUserName);
					dvOperationUser.setCreateTime(DateUtils.getNowDate());
					dvOperationUser.setUpdateBy(operationUserName);
					dvOperationUser.setUpdateTime(DateUtils.getNowDate());
					dvOperationUser.setDeptId("120");//开发时，还没有确定部门，但是设备投放部门id不能为空，先写OperationUserCode
					dvOperationUser.setCreateUserId(dvDeployment.getOperationUserCode());
					dvOperationUserService.insertDvOperationUser(dvOperationUser);//插入一条运维人员信息数据
				}
				//return R.fail("保存设备部署信息已保存，不需重复操作");
				SysRegion region = sysRegionService.selectSysRegionById(dvDeployment.getRegionId());
				if (region != null) {
					dvDeployment.setAncestors(region.getAncestors());
					Long parentId = region.getParentId();
					if (parentId != 0) {
						SysRegion parent = sysRegionService.selectSysRegionById(parentId.toString());
						dvDeployment.setAncestorsName(parent.getName());
					}
				}
				DvGroup group = dvGroupService.selectDvGroupById(Long.parseLong(dvDeployment.getGroupId()));
				if (group != null) {
					dvDeployment.setGroupName(group.getName());
					dvDeployment.setGroupAncestors(group.getAncestors());
				}
				dvDeployment.setDeptId(dvOperationUser.getDeptId());
				dvDeployment.setUpdateBy(dvDeployment.getOperationUserName());
				dvDeployment.setUpdateTime(DateUtils.getNowDate());
				dvDeployment.setStatus(0);
				return R.ok(dvDeploymentService.updateDvDeployment(dvDeployment));
			}
			return R.ok(dvDeploymentService.insertDvDeployment(dvDeployment));
		} catch (Exception e) {
			return R.fail(e.getMessage());
		}
	}

	@ApiOperation("获取投放部署信息")
	@GetMapping("/getDeploymentInfo")
	public R<DvDeployment> getDeploymentInfo(String deviceId) {
		try {
			if (StringUtils.isBlank(deviceId)) {
				return R.fail("设备id不能为空");
			}
			DvDeployment deployment = dvDeploymentService.selectDvDeploymentByDeviceId(deviceId);
			if (null != deployment) {
				return R.ok(deployment);
			} else {
				return R.fail("查无此部署设备");
			}
		} catch (Exception e) {
			return R.fail(e.getMessage());
		}
	}

/*	@ApiOperation("查询运维人员的接口")
	@GetMapping("/queryOperationUser")
	public R<List<DvOperationUser>> queryOperationUser(String name) {
		DvOperationUser dvOperationUser = new DvOperationUser();
		if (StringUtils.isNotBlank(name)) {
			dvOperationUser.setOperationUserName(name);
		}
		List<DvOperationUser> dvOperationUsers = dvOperationUserService
				.selectDvOperationUserByNameOrPhone(dvOperationUser);
		List<Map<String, String>> result = new ArrayList<>();
		for (DvOperationUser dvUser : dvOperationUsers) {
			Map<String, String> map = new HashMap<>();
			map.put("operationUserCode", dvUser.getOperationUserCode());
			map.put("operationUserName", dvUser.getOperationUserName());
			map.put("phoneNumber", dvUser.getPhoneNumber());
			result.add(map);
		}
		return R.ok(result);
	}
*/
	@ApiOperation("查询部署区域的接口")
	@GetMapping("/queryRegion")
	public R<RegionDto> queryRegion(Long parentId) {
		if (parentId == null) {
			parentId = 0L;
		}
		List<RegionDto> regionlist = sysRegionService.getRegionlist(parentId);
		return R.ok(regionlist);
	}

//    @ApiOperation("查询部署区域的接口")
//    @GetMapping("/queryRegion")
//    public R queryRegion(Long parentId) {
//        if (parentId == null) {
//            parentId = 0L;
//        }
//        Map<String, List<SysRegion>> regionTreeByPid = sysRegionService.findRegionTreeByPid(parentId);
//        List<SysRegion> sysRegions = regionTreeByPid.get(parentId.toString());
//        List<Map<String,String>> result = new ArrayList<>();
//        for (SysRegion region : sysRegions) {
//            Map<String,String> map = new HashMap<>();
//            map.put("id",region.getId());
//            map.put("code",region.getCode().toString());
//            map.put("name",region.getName());
//            Map<String, List<SysRegion>> child = sysRegionService.findRegionTreeByPid(Long.parseLong(region.getId()));
//            if(child.get(region.getId()).size() > 0 ){
//                map.put("hasChildren","1");
//            } else {
//                map.put("hasChildren","0");
//            }
//            result.add(map);
//        }
//        return R.ok(result);
//    }

//    @ApiOperation("查询分组的接口")
//    @GetMapping("/queryGroup")
//    public R queryGroup(Long parentId) {
//        if (parentId == null) {
//            parentId = 0L;
//        }
//        Map<Long, List<DvGroup>> dvGroupTreeByPid = dvGroupService.findDvGroupTreeByPid(parentId);
//        List<DvGroup> dvGroups = dvGroupTreeByPid.get(parentId);
//        List<Map<String,String>> result = new ArrayList<>();
//        for (DvGroup group : dvGroups) {
//            Map<String,String> map = new HashMap<>();
//            map.put("id",Long.toString(group.getId()));
//            map.put("name",group.getName());
//            Map<Long, List<DvGroup>> child = dvGroupService.findDvGroupTreeByPid(group.getId());
//            if(child.get(group.getId()).size()>0){
//                map.put("hasChildren","1");
//            } else {
//                map.put("hasChildren","0");
//            }
//            result.add(map);
//        }
//        return R.ok(result);
//    }

	@ApiOperation("查询分组的接口")
	@GetMapping("/queryGroup")
	public R queryGroup(@RequestParam("parentGroupId") Long parentCode, @RequestParam("regionCode") Long regionCode) {
		List<Map<String, String>> grouplist = dvGroupService.getGrouplist(regionCode, parentCode);
		return R.ok(grouplist);
	}

}
